﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Serialization;

namespace WJ.Infrastructure.Serializer
{
    public class XML
    {
        #region 将C#数据实体转化为xml数据

        /// <summary>
        /// 将C#数据实体转化为xml数据
        /// </summary>
        /// <param name="obj">要转化的数据实体</param>
        /// <returns>xml格式字符串</returns>
        public static string XmlSerialize<T>(T obj)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(typeof(T));

                //序列化对象  
                xml.Serialize(stream, obj);

                stream.Position = 0;
                using (StreamReader sr = new StreamReader(stream))
                {
                    string str = sr.ReadToEnd();

                    return str;
                }
            }
        }

        #endregion

        #region 将xml数据转化为C#数据实体

        /// <summary>
        /// 将xml数据转化为C#数据实体
        /// </summary>
        /// <param name="xml">符合xml格式的字符串</param>
        /// <returns>T类型的对象</returns>
        public static T XmlDeserialize<T>(string xml)
        {
            XmlSerializer xmldes = new XmlSerializer(typeof(T));

            using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml.ToCharArray())))
            {
                return (T) xmldes.Deserialize(stream);
            }
        }

        #endregion
    }
}